package com.bodacn.keypoint;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static java.lang.String.valueOf;


/**
 * Created by bodacn on 2016/6/15.
 */
public class FragmentProc extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
    public static String TAG=FragmentProc.class.getName();
    public static final int MSG_GetOrderOver = 1001;
    public static final int MSG_ERRMSG = 1002;
    public static final int MSG_ShowProcList = 1003;
    public static final int MSG_ShowEmpList = 1004;
    public static final int MSG_GETDEPART=1005;
    //全局变量
    String STORE_NAME = "Settings";
    String selectStyleID="";
    String selectOrderNo ="";
    String selectStyleNo="";
    String selectStyleSort="";
    //全局提示;
    Toast curToast;
    //全局变量
    SQLiteDatabase tmpdb;
    //布局元素;
    Button btn_SelectOrder, btn_AddPlace,btn_DelPlace,btn_AddEmpProc,btn_ClrEmpProc,btn_ReArrangeProc,btn_SaveProcScheme,btn_DownArrage,btn_SelectDepart;
    EditText edit_orderNo,edit_styleNo,edit_workDate;
    TextView text_titleOrderNo,text_titleStyleNo,text_titleStyleSort,text_titleSAMValue,text_titleTargetNum,text_titleTT;
    TextView text_ProcEmpCount,text_ProcBudgetOut,text_ProcBalanceRatio,text_WorkSection;
    ListView empListView,procListView;
    GridView arrMachineGrid;
    //全局变量
    String curLoginUserNo,curLoginUser,curFactory, curDepartNo="",curDepart="",curServiceUrl="";//操作员所属部门等信息;
    private ListView procOrderListGrid;
    int curOperateTime =600;//工作分钟
    String curSAMValue="0";
    private ProgressDialog waitDialog = null;
    GridView selectGirdView;
    //组别;
    private String curOrderNo ="", curStyleNo ="",curStyleSort="",curStyleID="",curWorkDate="",selEmpID="",selEmpNo="",selEmpName="", selDepart="",selDepartNo="",selPlaceNo="",CPUID="",WorkSection="";
    //TT,默认值为60;
    private int curWorkTT =60;
    private boolean NeedReLoad=false;
    //用于存储WebService返回的结果;
    private JSONArray OrderJSONArray,departJSON,detailJSON;
    //用于存放员工表、工序表;
    private JSONArray empList,procList,arrMachineList;
    //屏幕信息
    int screenwidth =0;     // 屏幕宽度（像素）
    int screenheight = 0;   // 屏幕高度（像素）
    float screendensity = 0;      // 屏幕密度（0.75 / 1.0 / 1.5）
    int screendensityDpi =0;  // 屏幕密度DPI（120 / 160 / 240）
    int curPlaceCount =30;
    //接口实现-------------------------------------------------------------------------->;
    //用于将Activity中的参数传给Fragment
    private Map<String,Object> fragmentParams=new HashMap<String,Object>();
    //用于与主Activity通讯;
    private Handler mainHandler;
    @Override
    public void onDetach() {
        super.onDetach();
        if (waitDialog!=null) waitDialog.dismiss();
    }


    public FragmentProc()
    {
        System.out.println("ProcFragment()");
    }




    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root=inflater.inflate(R.layout.fragment_proc,container,false);
        InitView(root);//按钮初始化;
        System.out.println("ProcFragment_onCreateView");
        return root;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //创建对话框，
        waitDialog=new ProgressDialog(getContext());
        waitDialog.setTitle("请稍等");
        waitDialog.setIndeterminate(true);
        //初始提醒;
        curToast = Toast.makeText(getContext(), "", Toast.LENGTH_LONG);
        curToast.setGravity(Gravity.CENTER, 0, 0);
        //获取屏幕信息
        DisplayMetrics metric = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metric);
        screenwidth = metric.widthPixels;     // 屏幕宽度（像素）
        screenheight = metric.heightPixels;   // 屏幕高度（像素）
        screendensity = metric.density;      // 屏幕密度（0.75 / 1.0 / 1.5）
        screendensityDpi = metric.densityDpi;  // 屏幕密度DPI（120 / 160 / 240）
        System.out.println("ProcFragment_onCreate");
        //得到Activity的Handler,用于发消息给主Activity;
        MainActivity activity=(MainActivity) getActivity();
        mainHandler=activity.mainHandler;
        //加接口监听
        activity.setTransProcParamsListener(new MainActivity.OnTransParamsListenerProc() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                if (mParams!=null) {
                    try {
                        Log.d("MSG","setTransProcParamsListener----TransParams--1");
                        String paramComm= mParams.get("ParamComm").toString();
                        Log.d("MSG","setTransProcParamsListener----paramComm--"+paramComm);
                        //根据参数显示订单信息;
                        if ((paramComm=="WorkSplit")||(paramComm=="SyncOrderInfo"))
                        {
                            Log.d("MSG","setTransProcParamsListener------------------------->showProcList");
                            //显示工序及员工列表;
                            NeedReLoad=true;
                        }
                        Log.d("MSG","setTransProcParamsListener----TransParams--2");
                        if (paramComm=="LoginParam")
                        {
                            //传递登陆参数信息;
                            curLoginUserNo=mParams.get("LoginUserNo").toString();
                            curLoginUser=mParams.get("LoginUser").toString();
                            curFactory=mParams.get("Factory").toString();
                            curDepartNo=mParams.get("DepartNo").toString();
                            curDepart=mParams.get("Depart").toString();
                            curOperateTime =(int)mParams.get("OperateTime");
                            curServiceUrl=mParams.get("ServiceUrl").toString();
                            curPlaceCount=Integer.parseInt(mParams.get("PlaceCount").toString());
                            CPUID=mParams.get("CPUID").toString();
                            WorkSection=mParams.get("WorkSection").toString();
                            text_WorkSection.setText(WorkSection);
                            btn_SelectDepart.setText("["+curDepartNo+"]"+curDepart);
                            selDepart=curDepart;
                            selDepartNo=curDepartNo;
                            refreshEmpList(curDepartNo);
                            if (departJSON==null) getDepartment(curFactory);
                            btn_DownArrage.postDelayed(new Runnable() {
                                public void run() {
                                    System.out.println("btn_DownArrage.postDelayed");
                                    if (tmpdb==null) OpenCreateDB();
                                    //显示生产单相关信息;
                                    Cursor curma = tmpdb.rawQuery("SELECT * FROM ProcMaList  ORDER BY ID Desc",null);
                                    if (curma.getCount()>0) {
                                        curma.moveToFirst();
                                        curStyleID=curma.getString(curma.getColumnIndex("StyleID"));
                                        text_titleOrderNo.setText(curma.getString(curma.getColumnIndex("OrderNo")));
                                        text_titleStyleNo.setText(curma.getString(curma.getColumnIndex("StyleNo")));
                                        text_titleStyleSort.setText(curma.getString(curma.getColumnIndex("StyleSort")));
                                        text_titleSAMValue.setText(curma.getString(curma.getColumnIndex("SAMValue")));
                                        text_titleTargetNum.setText(curma.getString(curma.getColumnIndex("TargetNum")));
                                        text_titleTT.setText(curma.getString(curma.getColumnIndex("TT")));
                                        curOrderNo=text_titleOrderNo.getText().toString();
                                        curStyleNo=text_titleStyleNo.getText().toString();
                                        curStyleSort=text_titleStyleSort.getText().toString();
                                        curma.close();
                                    }
                                }
                            }, 500);
                        }
                        Log.d("MSG","setTransProcParamsListener----TransParams--3");
                    } catch (Exception e) {
                        e.printStackTrace();
                        curToast.setText(e.getMessage());
                        curToast.show();
                    }
                }
            }
        });
    }


    //界面初始化;
    private void InitView(View v){
        //按键;
        System.out.println("A");
        btn_DownArrage=v.findViewById(R.id.btn_DownArrage);
        btn_DownArrage.setOnClickListener(this);
        btn_SelectOrder=(Button)v.findViewById(R.id.btn_SelectOrder);
        btn_SelectOrder.setOnClickListener(this);
        btn_ReArrangeProc=(Button)v.findViewById(R.id.btn_ReArrangeProc);
        btn_ReArrangeProc.setOnClickListener(this);
        btn_SaveProcScheme=(Button)v.findViewById(R.id.btn_SaveProcScheme);
        btn_SaveProcScheme.setOnClickListener(this);
        btn_AddEmpProc=v.findViewById(R.id.btn_AddEmpProc);
        btn_AddEmpProc.setOnClickListener(this);
        btn_ClrEmpProc=v.findViewById(R.id.btn_ClrEmpProc);
        btn_ClrEmpProc.setOnClickListener(this);
        btn_SelectDepart=v.findViewById(R.id.btn_SelectDepart);
        btn_SelectDepart.setOnClickListener(this);
        text_WorkSection=v.findViewById(R.id.text_WorkSection);
        System.out.println("B");
        edit_workDate=(EditText)v.findViewById(R.id.edit_workDate);
        edit_workDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {final Calendar calendar = Calendar.getInstance();
                final DatePickerDialog mDialog = new DatePickerDialog(getContext(), null, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                mDialog .setButton(DialogInterface.BUTTON_POSITIVE,"完成",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DatePicker datePicker = mDialog.getDatePicker();
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth();
                        int day = datePicker.getDayOfMonth();
                        calendar.set(year,month,day);
                        edit_workDate.setText(DateFormat.format("yyyy-MM-dd", calendar));
                    }
                });
                mDialog.setButton(DialogInterface.BUTTON_NEGATIVE,"取消",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("cancel~~cancel~~");
                    }
                });
                mDialog.setTitle("选择工作日期");
                mDialog.show();

            }
        });
        System.out.println("C");
        edit_workDate.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                curWorkDate=edit_workDate.getText().toString();
            }
        });
        text_titleOrderNo=(TextView)v.findViewById(R.id.text_titleOrderNo);
        text_titleStyleNo=(TextView)v.findViewById(R.id.text_titleStyleNo);
        text_titleStyleSort=(TextView)v.findViewById(R.id.text_titleStyleSort);
        text_titleSAMValue=(TextView)v.findViewById(R.id.text_titleSAMValue);
        text_titleTargetNum=(TextView)v.findViewById(R.id.text_titleTargetNum);
        text_titleTT=(TextView)v.findViewById(R.id.text_titleTT);
        text_ProcEmpCount=(TextView)v.findViewById(R.id.text_ProcEmpCount);
        text_ProcBudgetOut=(TextView)v.findViewById(R.id.text_ProcBudgetOut);
        text_ProcBalanceRatio=(TextView)v.findViewById(R.id.text_ProcBalanceRatio);
        System.out.println("D");
        //表格;
        procListView =v.findViewById(R.id.procListView);
        procListView.setOnItemClickListener(this);
        procListView.setOnItemLongClickListener(this);
        System.out.println("A");
        empListView=v.findViewById(R.id.empListView);
        empListView.setOnItemClickListener(this);
        //排车表;
        arrMachineGrid=(GridView)v.findViewById(R.id.arrMachineGrid);
        arrMachineGrid.setOnItemClickListener(this);
        arrMachineGrid.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                try {
                    selEmpNo = arrMachineList.optJSONObject(position).getString("EmpNo");
                    selEmpName = arrMachineList.optJSONObject(position).getString("EmpName");
                    selEmpID = arrMachineList.optJSONObject(position).getString("EmpID");
                    selPlaceNo=arrMachineList.optJSONObject(position).getString("PlaceNo");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                AlertDialog alertDialog = new AlertDialog.Builder(view.getContext())
                        .setTitle("系统提示").setMessage("您确定要删除选中位置员工及所有工序吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                //遍列位置对应的工序并选中;
                                try {
                                    arrMachineList.optJSONObject(position).put("EmpID","");
                                    arrMachineList.optJSONObject(position).put("EmpNo","");
                                    arrMachineList.optJSONObject(position).put("EmpName","");
                                    arrMachineList.optJSONObject(position).put("WorkNames","");
                                    arrMachineList.optJSONObject(position).put("MachineName","");
                                    tmpdb.execSQL("delete from EmpProcList Where PlaceNo=? ",new String[]{selPlaceNo});
                                    //清除所有已选中的工序;
                                    updateProcList(curDepartNo,curStyleID);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                        }).setNegativeButton("取消",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        return;
                                    }
                                }).create(); // 创建对话框
                alertDialog.show(); // 显示对话框
                return false;
            }
        });
        btn_AddPlace=v.findViewById(R.id. btn_AddPlace);
        btn_AddPlace.setOnClickListener(this);
        btn_DelPlace=v.findViewById(R.id. btn_DelPlace);
        btn_DelPlace.setOnClickListener(this);
        //置日期初始值;
        Date curDate = new Date(System.currentTimeMillis());
        edit_workDate.setText(DateFormat.format("yyyy-MM-dd", new Date(curDate.getTime())));

    }




    public final class ArrMachineGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public ArrMachineGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return arrMachineList.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return arrMachineList.get(position);
            } catch (JSONException e) {
                System.out.println("getItem取JSON数据出错!");
                e.printStackTrace();
                return  null;
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.fragment_proc_arrangeitem, null, false);
            int ct_max_background = getResources().getColor(R.color.ct_max_background);
            int ct_nor_background = getResources().getColor(R.color.ct_nor_background);
            try {
                TextView tv = (TextView) convertView.findViewById(R.id.text_ArrMch_PlaceNo);// 显示文字
                tv.setText(arrMachineList.optJSONObject(position).get("PlaceNo").toString());
                tv = (TextView) convertView.findViewById(R.id.text_ArrMch_EmpName);// 显示文字
                tv.setText(arrMachineList.optJSONObject(position).get("EmpName").toString());
                tv = (TextView) convertView.findViewById(R.id.text_ArrMch_WorkNames);// 显示文字
                tv.setText(arrMachineList.optJSONObject(position).get("WorkNames").toString());
                tv = (TextView) convertView.findViewById(R.id.text_ArrMch_MachineName);// 显示文字
                tv.setText(arrMachineList.optJSONObject(position).get("MachineName").toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return convertView;
        }
    }


    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        if (parent== procListView)
        {

        }
        return false;
    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    // 显示手机键盘
    private void showIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.showSoftInputFromInputMethod(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }




    //显示员工数据;
    private void showEmpList(String paramOrderNo,String paramStyleNo,String paramStyleID,String paramStyleSort)
    {
        selEmpID="";
        selEmpNo="";
        selEmpName="";
        if (tmpdb==null) OpenCreateDB();
        //更新当前款己安排SAM值;
        tmpdb.execSQL("update EmpList set EmpCT=0");
        tmpdb.execSQL("Delete from EmpTotalCT");
        tmpdb.execSQL("INSERT OR REPLACE INTO EmpTotalCT(DepartNo,EmpNo,OrderNo,StyleNo,EmpCT) Select DepartNo,EmpNo," +
                        "OrderNo,StyleNo,sum(SlowTime) EmpCT from EmpProcList where OrderNO=? and StyleNo=? Group by DepartNo,EmpNo,OrderNo,StyleNo",
                new String[]{paramOrderNo,paramStyleNo});
        tmpdb.execSQL("update EmpList Set EmpCT=(select EmpCT from EmpTotalCT where EmpList.EmpNo=EmpTotalCT.EmpNo)");
        //将数据加载到empList中;
        Cursor cur = tmpdb.rawQuery("SELECT * FROM EmpList ORDER BY ID", null);
        //更新人数显示;
        Log.d("showEmpList","showEmpList----检查员工数量！");
        int empCount=cur.getCount();
        Log.d("showEmpList","showEmpList----准备显示员工！"+empCount);
        try {
            //初始化员工列表;
            empList=new JSONArray("[]");
            while (cur.moveToNext()) {
                JSONObject empJSON = new JSONObject();
                empJSON.put("EmpID",cur.getString(cur.getColumnIndex("EmpID")));
                empJSON.put("EmpNo",cur.getString(cur.getColumnIndex("EmpNo")));
                empJSON.put("EmpName", cur.getString(cur.getColumnIndex("EmpName")));
                empJSON.put("EmpCT", cur.getInt(cur.getColumnIndex("EmpCT")));
                empJSON.put("SelSign","");
                empList.put(empJSON);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Log.d("msg","创建empList----Json出错");
        }
        cur.close();
        //显示到emGrid中;
        final EmpListAdapter empListAdapter=new EmpListAdapter(getContext());
        empListView.setAdapter(empListAdapter);
    }

    public final class EmpListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public EmpListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return empList.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return empList.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.fragment_proc_empitem, null, false);
            try {
                int textColor=getResources().getColor(R.color.text_black);
                TextView tv = convertView.findViewById(R.id.tv_empNo);// 显示文字
                tv.setGravity(Gravity.CENTER_VERTICAL);
                tv.setText(empList.optJSONObject(position).getString("EmpNo"));
                tv.setTextColor(textColor);
                tv = convertView.findViewById(R.id.tv_empName);// 显示文字
                tv.setGravity(Gravity.CENTER_VERTICAL);
                tv.setText(empList.optJSONObject(position).getString("EmpName"));
                tv.setTextColor(textColor);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.d("msg","EmpListAdapter_position:"+position);
            return convertView;
        }
    }


    //显示工序数据;
    private void showProcList()
    {
        System.out.println("showProcList");
        if (tmpdb==null) OpenCreateDB();
        //显示生产单相关信息;
        Cursor curma = tmpdb.rawQuery("SELECT * FROM ProcMaList  ORDER BY ID Desc",null);
        if (curma.getCount()>0) {
            curma.moveToFirst();
            text_titleOrderNo.setText(curma.getString(curma.getColumnIndex("OrderNo")));
            text_titleStyleNo.setText(curma.getString(curma.getColumnIndex("StyleNo")));
            text_titleStyleSort.setText(curma.getString(curma.getColumnIndex("StyleSort")));
            text_titleSAMValue.setText(curma.getString(curma.getColumnIndex("SAMValue")));
            text_titleTargetNum.setText(curma.getString(curma.getColumnIndex("TargetNum")));
            text_titleTT.setText(curma.getString(curma.getColumnIndex("TT")));
            curWorkTT=Integer.parseInt(curma.getString(curma.getColumnIndex("TT")));
            text_ProcEmpCount.setText(curma.getString(curma.getColumnIndex("EmpCount")));
            text_ProcBudgetOut.setText(curma.getString(curma.getColumnIndex("BudgetOut")));
            text_ProcBalanceRatio.setText(String.format("%.2f",curma.getDouble(curma.getColumnIndex("BalanceRatio")))+"%");
            curOrderNo=curma.getString(curma.getColumnIndex("OrderNo"));
            curStyleID=curma.getString(curma.getColumnIndex("StyleID"));
            curStyleNo=curma.getString(curma.getColumnIndex("StyleNo"));
            curStyleSort=curma.getString(curma.getColumnIndex("StyleSort"));
            updateBudgetOut(curDepartNo,curStyleID);
            //最少30个
            if (curma.getInt(curma.getColumnIndex("PlaceCount"))> curPlaceCount) curPlaceCount =curma.getInt(curma.getColumnIndex("PlaceCount"));
            //初始化机台表;
            tmpdb.execSQL("Delete from ArrangeMachine");
            for (int i = 1; i<= curPlaceCount; i++)
            {
                tmpdb.execSQL("insert into ArrangeMachine(PlaceNO) values(?)",new Object[]{i});
            }
        } else
        {
            curma.close();
            //刷新生产单;
            if (NeedReLoad==true) refreshProcList(curDepartNo,"","","","",edit_workDate.getText().toString());
            //初始化机台表;
            tmpdb.execSQL("Delete from ArrangeMachine");
            for (int i = 1; i<= curPlaceCount; i++)
            {
                tmpdb.execSQL("insert into ArrangeMachine(PlaceNO) values(?)",new Object[]{i});
            }
            //后续不再执行;
            return;
        }
        curma.close();
        //将数据加载到empList中;
        Cursor cur = tmpdb.rawQuery("SELECT * FROM ProcList WHERE DepartNo=?  and StyleID=? ORDER BY ID",
                new String[]{curDepartNo,curStyleID});
        try {
            //初始化工序列表;
            procList=new JSONArray("[]");
            while (cur.moveToNext()) {
                JSONObject empJSON = new JSONObject();
                empJSON.put("ArrangeID",cur.getString(cur.getColumnIndex("ArrangeID")));
                empJSON.put("ArrangeDeID",cur.getString(cur.getColumnIndex("ArrangeDeID")));
                empJSON.put("SchemeID",cur.getString(cur.getColumnIndex("SchemeID")));
                empJSON.put("OrderNo", cur.getString(cur.getColumnIndex("OrderNo")));
                empJSON.put("StyleNo", cur.getString(cur.getColumnIndex("StyleNo")));
                empJSON.put("StyleID", cur.getString(cur.getColumnIndex("StyleID")));
                empJSON.put("StyleSort", cur.getString(cur.getColumnIndex("StyleSort")));
                empJSON.put("StyleProID", cur.getString(cur.getColumnIndex("StyleProID")));
                empJSON.put("Part", cur.getString(cur.getColumnIndex("Part")));
                empJSON.put("PartIndex", cur.getString(cur.getColumnIndex("PartIndex")));
                empJSON.put("WorkLineNo", cur.getString(cur.getColumnIndex("WorkLineNo")));
                empJSON.put("WorkNo", cur.getString(cur.getColumnIndex("WorkNo")));
                empJSON.put("WorkName", cur.getString(cur.getColumnIndex("WorkName")));
                empJSON.put("MachineName", cur.getString(cur.getColumnIndex("MachineName")));
                empJSON.put("SlowTime", cur.getString(cur.getColumnIndex("SlowTime")));
                empJSON.put("WorkCT", cur.getString(cur.getColumnIndex("WorkCT")));
                empJSON.put("WorkArrEmps", cur.getString(cur.getColumnIndex("WorkArrEmps")));
                empJSON.put("WorkArrEmpNos", cur.getString(cur.getColumnIndex("WorkArrEmpNos")));
                empJSON.put("PlaceNos",cur.getString(cur.getColumnIndex("PlaceNos")));
                empJSON.put("BaseKey",cur.getString(cur.getColumnIndex("BaseKey")));
                empJSON.put("SelSign",(Boolean)false);
                procList.put(empJSON);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            curToast.setText(e.getMessage());
            curToast.show();
            Log.d("msg","创建empList----Json出错");
        }
        Log.d("msg","showProcList----记录条数为:"+cur.getCount());
        cur.close();
        //显示到工序中;
        final ProcGridAdapter procGridAdapter=new ProcGridAdapter(getContext());
        procListView.setAdapter(procGridAdapter);
        //显示完工序后、显示员工信息;
        showArrMachineGrid(curDepartNo,curStyleID);
    }


    //显示工序安排;
    private void showArrangeActivity(){
        //将登陆信息、车间、组别、工作时间等信息带过去。
        Intent arrangeActivity=new Intent(getActivity(),ArrangeActivity.class);
        //简单参数通过Intent的Extras传递;
        Bundle paramBundle = new Bundle();
        paramBundle.putString("DepartNo", curDepartNo);
        paramBundle.putString("OrderNo", curOrderNo);
        paramBundle.putString("StyleNo", curStyleNo);
        paramBundle.putString("StyleID", curStyleID);
        paramBundle.putString("StyleSort",curStyleSort);
        paramBundle.putInt("TT", curWorkTT);
        arrangeActivity.putExtras(paramBundle);
        //启动主界面;
        startActivity(arrangeActivity);
    }
    //刷新员工列表;
    private void refreshEmpList(String departNoParam)
    {
        waitDialog.setMessage("准备从网络获取员工信息....");
        Log.d("refreshEmpList","refreshEmpList---------------Enter");
        //执行SQL过程
        String SqlComm="Exec ScenePAD_GetEmpList  @DepartmentNo='" + departNoParam + "',@GetContext=1";
        //调用WebService过程并处理界面更新;
        ReadEmpSQLData(SqlComm);
        Log.d("refreshEmpList","refreshEmpList---------------Over");
    }


    //刷新订单列表;
    private void refreshOrderList(String departParam,String orderParam,String styleParam,String SortParam)
    {
        selectStyleID="";
        selectOrderNo ="";
        selectStyleNo="";
        //清空原订单记录;
        try {
            OrderJSONArray=new JSONArray("[]");
            //显示到工序中;
            final SelectOrderListAdapter selectOrderListAdapter=new SelectOrderListAdapter(getContext());
            procOrderListGrid.setAdapter(selectOrderListAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NeedReLoad=false;
        waitDialog.setMessage("准备从网络获取参考合约信息....");
        //执行SQL过程
        String SqlComm="Exec ScenePAD_GetSelectOrder @DepartNo='" + departParam + "',@OrderNo='"+orderParam+"',@StyleNo='"+styleParam+"',@StyleSort='"+SortParam+"',@UserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    //复制安排表;
    private void  CopyStyleArrange(String ParamDepartNo,String ParamTarOrderNo,String ParamTarStyleNo,String ParamTarStyleSort,String ParamTarStyleID,String  ParamSurOrderNO,String ParamSurStyleNo,String ParamSurStyleID,String paramSurStyleSort){
        waitDialog.setMessage("请求服务器进行工序安排复制，请稍等....");
        //执行SQL过程
        String SqlComm="Exec ScenePAD_CopyStyleArrange @DepartNo='" + ParamDepartNo + "',@TarOrderNo='"+ParamTarOrderNo+"',@TarStyleNo='"+ParamTarStyleNo+"',@TarStyleSort='"+ParamTarStyleSort+"',@TarStyleID='"+ParamTarStyleID
                +"',@SurOrderNo='"+ParamSurOrderNO+"',@SurStyleNo='"+ParamSurStyleNo+"',@SurStyleID='"+ParamSurStyleID+"',@SurStyleSort='"+paramSurStyleSort+"',@UserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }
    //显示可以复制的订单列表;
    private void showOrderList() {
        //显示到工序中;
        final SelectOrderListAdapter selectOrderListAdapter=new SelectOrderListAdapter(getContext());
        procOrderListGrid.setAdapter(selectOrderListAdapter);
    }

    //刷新工序列表;
    private void refreshProcList(String departNoParam,String orderParam,String styleParam,String paramStyleID,String paramStyleSort,String paramWorkDate)
    {
        NeedReLoad=false;
        waitDialog.setMessage("准备从网络获取工序信息....");
        curOrderNo=orderParam;
        curStyleNo=styleParam;
        curStyleID=paramStyleID;
        curStyleSort=paramStyleSort;
        //执行SQL过程
        String SqlComm="Exec ScenePAD_GetProcList @DepartmentNo='" + departNoParam + "',@OrderNo='"+orderParam+"',@StyleNo='"+styleParam
                +"',@StyleID='"+paramStyleID+"',@StyleSort='"+paramStyleSort+"',@WorkDate='"+paramWorkDate+"',@WorkSection='"+WorkSection+"'";
        //调用WebService过程并处理界面更新;
        ReadProcSQLData(SqlComm);
    }


    //直接连获取数据，与Handler配套使用;
    private void ReadEmpSQLData(final String SQLComm) {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = ToolUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    //往界面转数据;
                    //将数据存到数据库中;
                    if (tmpdb == null) OpenCreateDB();
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        //SQL异常;
                        if (jsonArray.optJSONObject(0).has("SQLExcept")==true)  {
                            //关闭ProgressDialog
                            Message msg = new Message();
                            msg.what = MSG_ERRMSG;
                            Bundle bundle=new Bundle();
                            bundle.putString("MSG",jsonArray.optJSONObject(0).getString("SQLMessage"));
                            msg.setData(bundle);
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                            return;
                        }
                        //将数据存到数据库中;
                        if (tmpdb == null) OpenCreateDB();
                        tmpdb.execSQL("Delete from EmpList");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            tmpdb.execSQL("INSERT INTO EmpList(ID,DepartNo,EmpID,EmpNo,EmpName) VALUES (NULL,?,?,?,?)",
                                    new Object[]{jsonArray.optJSONObject(i).getString("DepartNo"), jsonArray.optJSONObject(i).getString("EmpNo"),
                                            jsonArray.optJSONObject(i).getString("EmpNo"), jsonArray.optJSONObject(i).getString("EmpName")});
                        }
                        //关闭ProgressDialog
                        Message msg = new Message();
                        msg.what = MSG_ShowEmpList;
                        fragmentHandler.removeMessages(msg.what);
                        fragmentHandler.sendMessage(msg);
                        Log.d("ReadEmpSQLData","onPostExecute------------------------->showEmpList:1");
                    } else {
                        Log.d("ReadEmpSQLData","onPostExecute------------------------->showEmpList:2");
                        //清空数据;
                        empList=new JSONArray("[]");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //关闭ProgressDialog
                    Message msg = new Message();
                    msg.what = MSG_ERRMSG;
                    Bundle bundle=new Bundle();
                    bundle.putString("MSG",e.getMessage());
                    msg.setData(bundle);
                    fragmentHandler.removeMessages(msg.what);
                    fragmentHandler.sendMessage(msg);
                }
            }

        };
        new Thread(run).start();
    }

    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                //消息处理;
                System.out.println("收到的消息是："+msg.what);
                //关闭ProgressDialog
                if (waitDialog.isShowing()) waitDialog.hide();
                int msgId = msg.what;
                switch (msgId) {
                    case MSG_GETDEPART:
                        break;
                    case MSG_GetOrderOver:
                        showOrderList();
                        break;
                    case MSG_ERRMSG:
                        Bundle bundle=msg.getData();
                        curToast.setText(bundle.getString("MSG"));
                        curToast.show();
                        break;
                    case MSG_ShowProcList:
                        //显示数据,不能放到外面，会引起死循环;
                        showProcList();
                        break;
                    case MSG_ShowEmpList:
                        //显示员工;
                        showEmpList(curOrderNo,curStyleNo,curStyleID,curStyleSort);
                        break;
                    default:
                        break;
                }
            }
        }
    };
    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = ToolUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    String OperType="";
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)){
                        if (jsonArray.optJSONObject(0).has("OperType")==true)  OperType=jsonArray.optJSONObject(0).getString("OperType");
                        if (jsonArray.optJSONObject(0).has("OPERTYPE")==true)  OperType=jsonArray.optJSONObject(0).getString("OPERTYPE");
                        //SQL异常;
                        if (jsonArray.optJSONObject(0).has("SQLExcept")==true)  {
                            //关闭ProgressDialog
                            Message msg = new Message();
                            msg.what = MSG_ERRMSG;
                            Bundle bundle=new Bundle();
                            bundle.putString("MSG",jsonArray.optJSONObject(0).getString("SQLMessage"));
                            msg.setData(bundle);
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                            return;
                        }
                        Log.d("msg","onPostExecute--------------------1");
                        //返回的为订单数据;
                        if (jsonArray.optJSONObject(0).has("GetSelectOrder")==true)
                        {
                            Log.d("msg","GetSelectOrder--------------------2");
                            OrderJSONArray=jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_GetOrderOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (OperType.equals("GETDEPART")) {
                            departJSON= jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_GETDEPART;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                    } else{
                        //关闭ProgressDialog
                        Message msg = new Message();
                        msg.what = MSG_ERRMSG;
                        Bundle bundle=new Bundle();
                        bundle.putString("MSG","未返回数据");
                        msg.setData(bundle);
                        fragmentHandler.removeMessages(msg.what);
                        fragmentHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //关闭ProgressDialog
                    Message msg = new Message();
                    msg.what = MSG_ERRMSG;
                    Bundle bundle=new Bundle();
                    bundle.putString("MSG",e.getMessage());
                    msg.setData(bundle);
                    fragmentHandler.removeMessages(msg.what);
                    fragmentHandler.sendMessage(msg);
                }
            }

        };
        new Thread(run).start();

    }

    //直接连获取数据，与Handler配套使用;
    private void ReadProcSQLData(final String SQLComm) {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = ToolUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    //往界面转数据;
                    //将数据存到数据库中;
                    if (tmpdb == null) OpenCreateDB();
                    tmpdb.execSQL("Delete from ProcMaList");
                    tmpdb.execSQL("Delete from ProcList ");
                    tmpdb.execSQL("Delete from EmpProcList ");
                    if ((jsonArray!=null)&&(jsonArray.length()>0)){
                        //SQL异常;
                        if (jsonArray.optJSONObject(0).has("SQLExcept")==true)  {
                            //关闭ProgressDialog
                            Message msg = new Message();
                            msg.what = MSG_ERRMSG;
                            Bundle bundle=new Bundle();
                            bundle.putString("MSG",jsonArray.optJSONObject(0).getString("SQLMessage"));
                            msg.setData(bundle);
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                            return;
                        }
                        Log.d("msg","onPostExecute:jsonArray长度为"+jsonArray.length()+"，准备转换。。。。。。。。");
                        //往界面转数据;
                        OrderJSONArray = jsonArray;
                        String tmpStyleID=OrderJSONArray.optJSONObject(0).getString("StyleID");
                        //生成ProcMaList记录;
                        tmpdb.execSQL("INSERT INTO ProcMaList(ArrangeID,DepartNo,OrderNo,StyleNo,StyleID,StyleSort,WorkDate,OrderNumber,SAMValue,TargetNum,TT,CT,EmpCount,BudgetOut,BalanceRatio,UpdateTime)" +
                                        " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,datetime('now','localtime'))",
                                new Object[]{OrderJSONArray.optJSONObject(0).getString("ArrangeID"), OrderJSONArray.optJSONObject(0).getString("DepartNo")
                                        , OrderJSONArray.optJSONObject(0).getString("OrderNo"), OrderJSONArray.optJSONObject(0).getString("StyleNo")
                                        , OrderJSONArray.optJSONObject(0).getString("StyleID"), OrderJSONArray.optJSONObject(0).getString("StyleSort"), OrderJSONArray.optJSONObject(0).getString("WorkDate")
                                        , OrderJSONArray.optJSONObject(0).getInt("OrderNumber"), OrderJSONArray.optJSONObject(0).getLong("SAMValue")
                                        , OrderJSONArray.optJSONObject(0).getInt("TargetNum"), OrderJSONArray.optJSONObject(0).getInt("TT")
                                        , OrderJSONArray.optJSONObject(0).getDouble("CT"), OrderJSONArray.optJSONObject(0).getInt("EmpCount")
                                        , OrderJSONArray.optJSONObject(0).getInt("BudgetOut"), OrderJSONArray.optJSONObject(0).getLong("BalanceRatio")});
                        Log.d("msg","onPostExecute:生成ProcMaList记录完成...........");
                        //保存相关记录;
                        for (int i = 0; i < OrderJSONArray.length(); i++) {
                            //保存工序数据;
                            tmpdb.execSQL("INSERT INTO ProcList(ArrangeID,ArrangeDeID,SchemeID,DepartNo,OrderNo,StyleNo,StyleID,StyleSort,WorkDate,StyleProID,Part,PartIndex,WorkLineNo,WorkNo,WorkName,MachineName,SlowTime,WorkCT,WorkArrEmps,WorkArrEmpNos,PlaceNos,BaseKey) " +
                                            "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                                    new Object[]{OrderJSONArray.optJSONObject(i).getString("ArrangeID"), OrderJSONArray.optJSONObject(i).getString("ArrangeDeID")
                                            , OrderJSONArray.optJSONObject(i).getString("SchemeID")
                                            , OrderJSONArray.optJSONObject(i).getString("DepartNo"), OrderJSONArray.optJSONObject(i).getString("OrderNo")
                                            , OrderJSONArray.optJSONObject(i).getString("StyleNo"), OrderJSONArray.optJSONObject(i).getString("StyleID")
                                            , OrderJSONArray.optJSONObject(i).getString("StyleSort"), OrderJSONArray.optJSONObject(i).getString("WorkDate")
                                            , OrderJSONArray.optJSONObject(i).getString("StyleProID"), OrderJSONArray.optJSONObject(i).getString("Part")
                                            , OrderJSONArray.optJSONObject(i).getString("PartIndex"), OrderJSONArray.optJSONObject(i).getString("WorkLineNo")
                                            , OrderJSONArray.optJSONObject(i).getString("WorkNo")
                                            , OrderJSONArray.optJSONObject(i).getString("WorkName"), OrderJSONArray.optJSONObject(i).getString("MachineName")
                                            , OrderJSONArray.optJSONObject(i).getString("SlowTime"), OrderJSONArray.optJSONObject(i).getString("WorkCT")
                                            , OrderJSONArray.optJSONObject(i).getString("WorkArrEmps"), OrderJSONArray.optJSONObject(i).getString("WorkArrEmpNos")
                                            ,OrderJSONArray.optJSONObject(i).getString("PlaceNos"),(OrderJSONArray.optJSONObject(i).get("BaseKey").equals(null)?"false": OrderJSONArray.optJSONObject(i).getString("BaseKey"))
                                    });
                            //保存安排数据
                            String WorkArrEmpNos = (OrderJSONArray.optJSONObject(i).get("WorkArrEmpNos").equals(null)?"": OrderJSONArray.optJSONObject(i).getString("WorkArrEmpNos"));
                            String WorkArrEmps=(OrderJSONArray.optJSONObject(i).getString("WorkArrEmps").equals(null)?"": OrderJSONArray.optJSONObject(i).getString("WorkArrEmps"));
                            String WorkArrPlaceNos=(OrderJSONArray.optJSONObject(i).getString("PlaceNos").equals(null)?"": OrderJSONArray.optJSONObject(i).getString("PlaceNos"));
                            String[] ArrEmpNos = null;
                            String[] ArrEmps = null;
                            String[] ArrPlaceNos = null;
                            ArrEmpNos = WorkArrEmpNos.split(",");
                            ArrEmps = WorkArrEmps.split(",");
                            ArrPlaceNos = WorkArrPlaceNos.split(",");
                            String placeNo="0";
                            if (!ArrEmpNos.equals(null)) {
                                for (int j = 0; j < ArrEmpNos.length; j++) {
                                    //长度为0的也会分解成长度为1的数据;
                                    if (ArrEmpNos[j].length()>0) {
                                        if (ArrPlaceNos.length > j) placeNo = ArrPlaceNos[j];
                                        else placeNo = "0";
                                        tmpdb.execSQL("INSERT INTO EmpProcList(DepartNo,EmpNo,EmpName,OrderNo,StyleNo,StyleID,StyleSort,WorkDate,StyleProID,WorkLineNo,WorkNo,WorkName,MachineName,SlowTime,PlaceNo) " +
                                                        "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                                                new Object[]{OrderJSONArray.optJSONObject(i).getString("DepartNo"), ArrEmpNos[j],ArrEmps[j], OrderJSONArray.optJSONObject(i).getString("OrderNo")
                                                        , OrderJSONArray.optJSONObject(i).getString("StyleNo"), OrderJSONArray.optJSONObject(i).getString("StyleID")
                                                        , OrderJSONArray.optJSONObject(i).getString("StyleSort"), OrderJSONArray.optJSONObject(i).getString("WorkDate")
                                                        , OrderJSONArray.optJSONObject(i).getString("StyleProID"), OrderJSONArray.optJSONObject(i).getInt("WorkLineNo")
                                                        , OrderJSONArray.optJSONObject(i).getString("WorkNo"), OrderJSONArray.optJSONObject(i).getString("WorkName")
                                                        , OrderJSONArray.optJSONObject(i).getString("MachineName"), OrderJSONArray.optJSONObject(i).getInt("SlowTime"), placeNo});
                                    }
                                }
                            }
                        }
                        Cursor curma = tmpdb.rawQuery("SELECT Max(PlaceNo) PlaceCount FROM EmpProcList  ORDER BY ID Desc",null);
                        if (curma.getCount()>0) {
                            curma.moveToFirst();
                            int count=curma.getInt(curma.getColumnIndex("PlaceCount"));
                            //更新总数量;
                            tmpdb.execSQL("Update ProcMaList Set PlaceCount=? where StyleID=?",new String[]{valueOf(count),tmpStyleID});
                        }
                        curma.close();
                        Log.d("msg","onPostExecute:转换完成.......准备显示工序");
                        //关闭ProgressDialog
                        Message msg = new Message();
                        msg.what = MSG_ShowProcList;
                        fragmentHandler.removeMessages(msg.what);
                        fragmentHandler.sendMessage(msg);
                    } else{
                        //关闭ProgressDialog
                        Message msg = new Message();
                        msg.what = MSG_ERRMSG;
                        Bundle bundle=new Bundle();
                        bundle.putString("MSG","未返回数据");
                        msg.setData(bundle);
                        fragmentHandler.removeMessages(msg.what);
                        fragmentHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //关闭ProgressDialog
                    Message msg = new Message();
                    msg.what = MSG_ERRMSG;
                    Bundle bundle=new Bundle();
                    bundle.putString("MSG",e.getMessage());
                    msg.setData(bundle);
                    fragmentHandler.removeMessages(msg.what);
                    fragmentHandler.sendMessage(msg);
                }
            }

        };
        new Thread(run).start();

    }

    //从员工工序安排表中更新
    private void organizeProcList(String paramDepartNo,String paramStyleID){
        for(int i=0;i<procList.length();i++) {
            Log.d("onClick","A-------------------");
            try {
                //取消选择状态;
                procList.getJSONObject(i).put("SelSign",false);
                String StyleProID=procList.getJSONObject(i).getString("StyleProID");
                //添加至工序列表;
                String WorkArrEmps="";
                String WorkArrEmpNos="";;
                String PlaceNos="";
                Cursor curq=tmpdb.rawQuery("Select * from EmpProcList where DepartNo=? and StyleID=? and StyleProID=?"
                        ,new String[]{paramDepartNo,paramStyleID,StyleProID});
                if (curq.getCount()>0) {
                    while (curq.moveToNext()) {
                        String EmpNo= curq.getString(curq.getColumnIndex("EmpNo"));
                        String EmpName= curq.getString(curq.getColumnIndex("EmpName"));
                        String PlaceNo= curq.getString(curq.getColumnIndex("PlaceNo"));
                        if (WorkArrEmps.length() > 0) WorkArrEmps = WorkArrEmps + ',' + EmpName;
                        else WorkArrEmps = EmpName;
                        if (WorkArrEmpNos.length() > 0) WorkArrEmpNos = WorkArrEmpNos + ',' + EmpNo;
                        else WorkArrEmpNos = EmpNo;
                        if (PlaceNos.length() > 0) PlaceNos = PlaceNos + ',' + PlaceNo;
                        else PlaceNos = PlaceNo;
                    }
                }
                procList.getJSONObject(i).put("WorkArrEmps",WorkArrEmps);
                procList.getJSONObject(i).put("WorkArrEmpNos",WorkArrEmpNos);
                procList.getJSONObject(i).put("PlaceNos",PlaceNos);
                //更新相关字段;
                tmpdb.execSQL("UPDATE ProcList SET WorkArrEmps=?,WorkArrEmpNos=?,PlaceNos=? WHERE StyleProID=? and DepartNo=?  and StyleID=?",
                        new String[]{WorkArrEmps, WorkArrEmpNos, PlaceNos, StyleProID, paramDepartNo, paramStyleID});
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }
    //显示员工数据;
    private void showArrMachineGrid(String paramDepart,String paramStyleID)
    {
        System.out.println("showArrMachineGrid----------------------------->");
        selPlaceNo="";
        int curPlaceNo=0;
        String empID="",empNo="",empName="",workNames="",machineName="";
        if (tmpdb==null) OpenCreateDB();
        //更新当前款己安排SAM值;
        tmpdb.execSQL("Update ArrangeMachine Set EmpID=?,EmpNo=?,EmpName=?,MachineName=?,WorkNames=?",new String[]{"","","","",""});
        //生成安排表;
        Cursor cur = tmpdb.rawQuery("SELECT EmpNo EmpID,EmpNo,EmpName,WorkLineNo,WorkNo,WorkName,MachineName,PlaceNo FROM  EmpProcList " +
                " where DepartNo=? and StyleID=? ORDER BY PlaceNo", new String[]{paramDepart,paramStyleID});
        while (cur.moveToNext()) {
            if (curPlaceNo!=cur.getInt(cur.getColumnIndex("PlaceNo")))
            {
                curPlaceNo=cur.getInt(cur.getColumnIndex("PlaceNo"));
                workNames="";
            }
            empID=cur.getString(cur.getColumnIndex("EmpID"));
            empNo=cur.getString(cur.getColumnIndex("EmpNo"));
            empName=cur.getString(cur.getColumnIndex("EmpName"));
            machineName=cur.getString(cur.getColumnIndex("MachineName"));
            String tmpWorkNo=cur.getString(cur.getColumnIndex("WorkNo"));
            String tmpWorkName=cur.getString(cur.getColumnIndex("WorkName"));
            if (tmpWorkName.length()>14) tmpWorkName=tmpWorkName.substring(0,14)+"...";
            if (workNames.length()>0) workNames=workNames+"\r\n"+tmpWorkNo+"."+tmpWorkName;else workNames=tmpWorkNo+"."+tmpWorkName;
            tmpdb.execSQL("Update ArrangeMachine Set EmpID=?,EmpNo=?,EmpName=?,MachineName=?,WorkNames=? where PlaceNo=?",new Object[]{empID,empNo,empName,machineName,workNames,curPlaceNo});
        }
        //将安排情况放入数组arrMachineList;
        cur = tmpdb.rawQuery("SELECT * FROM ArrangeMachine ORDER BY PlaceNo",null);
        try {
            //初始化员工列表;
            arrMachineList=new JSONArray("[]");
            while (cur.moveToNext()) {
                JSONObject empJSON = new JSONObject();
                empJSON.put("SelSign",false);
                empJSON.put("PlaceNo",cur.getString(cur.getColumnIndex("PlaceNo")));
                empJSON.put("EmpID",cur.getString(cur.getColumnIndex("EmpID")));
                empJSON.put("EmpNo",cur.getString(cur.getColumnIndex("EmpNo")));
                empJSON.put("EmpName",cur.getString(cur.getColumnIndex("EmpName")));
                empJSON.put("MachineName", cur.getString(cur.getColumnIndex("MachineName")));
                empJSON.put("WorkNames", cur.getString(cur.getColumnIndex("WorkNames")));
                arrMachineList.put(empJSON);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Log.d("msg","创建arrMachineList----Json出错");
        }
        cur.close();
        //显示到arrMachineGrid中;
        final ArrMachineGridAdapter arrMachineGridAdapter=new ArrMachineGridAdapter(getContext());
        arrMachineGrid.setAdapter(arrMachineGridAdapter);
    }

    @Override
    public void onClick(View v) {
        hideIM(v);
        switch (v.getId())
        {
            case R.id.btn_SelectDepart:
                showSelectDepart();
                break;
            case R.id.btn_DownArrage:
                if ((curOrderNo.length()==0)&&(curOrderNo.length()==0))
                {
                    curToast.setText("请先选择款式信息!");
                    curToast.show();
                    return;
                }
                if (edit_workDate.length()==0)
                {
                    curToast.setText("请选择您要下载的安排日期！");
                    curToast.show();
                    return;
                }
                NeedReLoad=true;
                refreshProcList(curDepartNo,curOrderNo,curStyleNo,curStyleID,curStyleSort,curWorkDate);
                break;
            case R.id.btn_ClrEmpProc:
                for(int i=0;i<procList.length();i++) {
                    Log.d("onClick", "A-------------------");
                    try {
                        if (procList.getJSONObject(i).getBoolean("SelSign") == true) {
                            //取消选择状态;
                            procList.getJSONObject(i).put("SelSign", false);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                //更新工序列表;
                ((BaseAdapter)procListView.getAdapter()).notifyDataSetChanged();
                break;
            case R.id.btn_AddEmpProc:
                if (selPlaceNo.length()==0)
                {
                    curToast.setText("请选择排车位置!");
                    curToast.show();
                    return;
                }
                if (selEmpNo.length()==0)
                {
                    curToast.setText("请选择员工!");
                    curToast.show();
                    return;
                }
                //判断机台上是否有人;
                int placeIndex=Integer.parseInt(selPlaceNo)-1;
                try {
                    if ((arrMachineList.getJSONObject(placeIndex).getString("EmpNo").equals(selEmpNo)==false)
                            &&(arrMachineList.getJSONObject(placeIndex).getString("EmpNo").length()>0)){
                        AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                                .setTitle("系统提示").setMessage("车位上已经安排其他员工，请长按位置行清除工序！")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                }).create();

                        alertDialog.show(); // 显示对话框
                    }else
                    {
                        btn_AddEmpProc.setBackground(getResources().getDrawable(R.drawable.button_selector));
                        //增加工序到员工名下;
                        if (selEmpID.length()>0) AddEmpProc();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btn_SelectOrder:
                selectStyle();
                break;
            case R.id.btn_ViewProcScheme:
                //刷新工序;
                if (curStyleNo.length()==0)
                {
                    curToast.setText("请选择您所需要的合约！");
                    curToast.show();
                    return;
                }
                //显示安排情况;
                showArrangeActivity();
                break;
            case R.id.btn_ReArrangeProc:
                if ((curStyleNo.length()==0)&&(curOrderNo.length()==0))
                {
                    curToast.setText("请先过滤并选择您所需要的款号！");
                    curToast.show();
                    return;
                }
                AlertDialog alertDialog = new AlertDialog.Builder(v.getContext())
                        .setTitle("系统提示").setMessage("您确定要清空本机所有员工工序安排吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                waitDialog.setMessage("正在删除本机所有员工工序按排，请稍等...");
                                //清空所有员工安排;
                                ReEmpProc(curDepartNo,curOrderNo,curStyleNo,curStyleID,curStyleSort,curWorkDate);
                            }
                        }).setNegativeButton("取消",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        return;
                                    }
                                }).create(); // 创建对话框
                alertDialog.show(); // 显示对话框
                break;
            case R.id.btn_SaveProcScheme:
                btn_SaveProcScheme.setBackground(getResources().getDrawable(R.drawable.button_selector));
                if ((curStyleNo.length()==0)&&(curOrderNo.length()==0))
                {
                    curToast.setText("请选过滤并选择您所需要的合约！");
                    curToast.show();
                    return;
                }
                //保存工序;
                SaveProcArrange(curDepartNo,curOrderNo,curStyleNo,curStyleID,curStyleSort,curWorkDate);
                break;
            case R.id.btn_AddPlace:
                if ((selPlaceNo.length()>0)&&(isNumer(selPlaceNo))) {
                    waitDialog.setMessage("添加位置,请稍等.....");
                    waitDialog.show();
                    //将数据加载到empList中;
                    Cursor cur = tmpdb.rawQuery("SELECT Max(PlaceNo) MaxPlaceNo FROM ArrangeMachine", null);
                    if (cur.getCount()>0){
                        cur.moveToNext();
                        Integer maxPlaceNo=cur.getInt(cur.getColumnIndex("MaxPlaceNo"));
                        tmpdb.execSQL("insert into ArrangeMachine(PlaceNo) values(?)",new String[]{String.valueOf(maxPlaceNo+1)});
                        curPlaceCount =maxPlaceNo+1;
                        tmpdb.execSQL("update ProcMaList Set PlaceCount=?",new String[]{String.valueOf(curPlaceCount)});
                        JSONObject empJSON = new JSONObject();
                        try {
                            empJSON.put("SelSign",false);
                            empJSON.put("PlaceNo",String.valueOf(maxPlaceNo+1));
                            empJSON.put("EmpID","");
                            empJSON.put("EmpNo","");
                            empJSON.put("EmpName","");
                            empJSON.put("MachineName", "");
                            empJSON.put("WorkNames", "");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        arrMachineList.put(empJSON);
                        //将当前选中的位置号都加1;
                        tmpdb.execSQL("update EmpProcList Set PlaceNo=PlaceNo+1 where PlaceNo>?",new String[]{selPlaceNo});
                        //重新组组工序表
                        organizeProcList(curDepartNo,curStyleID);
                        //重新显示工序及设备安排
                        showProcList();
                        if (waitDialog.isShowing()) {
                            waitDialog.hide();
                        }
                    }else {
                        curToast.setText("请先选择位置!");
                        curToast.show();
                    }

                }
                break;
            case R.id.btn_DelPlace:
                if ((selPlaceNo.length()>0)&&(isNumer(selPlaceNo))) {
                    waitDialog.setMessage("删除位置,请稍等.....");
                    waitDialog.show();

                    //将数据加载到empList中;
                    Cursor cur2 = tmpdb.rawQuery("SELECT Max(PlaceNo) MaxPlaceNo FROM ArrangeMachine", null);
                    if (cur2.getCount()>0){
                        cur2.moveToNext();
                        Integer maxPlaceNo=cur2.getInt(cur2.getColumnIndex("MaxPlaceNo"));
                        if (maxPlaceNo>=Integer.valueOf(selPlaceNo)) {
                            tmpdb.execSQL("delete from ArrangeMachine where PlaceNo=?", new String[]{String.valueOf(maxPlaceNo)});
                            arrMachineList.remove(maxPlaceNo - 1);
                            curPlaceCount =maxPlaceNo-1;
                            tmpdb.execSQL("update ProcMaList Set PlaceCount=?",new String[]{String.valueOf(curPlaceCount)});
                            //将当前选中的位置号都加1;
                            tmpdb.execSQL("delete from EmpProcList where PlaceNo=?", new String[]{selPlaceNo});
                            tmpdb.execSQL("update EmpProcList Set PlaceNo=PlaceNo-1 where PlaceNo>=?", new String[]{selPlaceNo});
                            if (maxPlaceNo==Integer.valueOf(selPlaceNo)){
                                selPlaceNo=String.valueOf(maxPlaceNo-1);
                            }
                            //重新组组工序表
                            organizeProcList(curDepartNo, curStyleID);
                            //重新显示工序及设备安排
                            showProcList();

                        }
                    }
                    if (waitDialog.isShowing()) {
                        waitDialog.hide();
                    }
                }else {
                    curToast.setText("请先选择位置!");
                    curToast.show();
                }
                break;
            default:
                break;
        }
    }

    //刷新缸布列表;
    private void getDepartment(String paramWorkShop)
    {
        System.out.println("getDepartment------------------------------------->");
        //执行SQL过程
        String SqlComm = "Exec ScenePAD_GetDepart @OPERTYPE='GETDEPART',@WorkShop='"+paramWorkShop+"',@UserNo='"+curLoginUserNo+ "',@CPUID='"+CPUID+"'";
        ReadSQLData(SqlComm);
    }

    //显示工序选择
    private void showSelectDepart(){
        if ((departJSON==null)||(departJSON.length()==0)){
            curToast.setText("没有车间组别信息!");
            curToast.show();
            if (curFactory!=null) getDepartment(curFactory);
            return;
        }
        //创建布局
        String dgCaption="组别选择";
        LayoutInflater inflater=this.getLayoutInflater();
        final View selectGrid=inflater.inflate(R.layout.select_grid, null);
        //Activity.findViewById最终还是会调用View.findViewById
        selectGirdView=selectGrid.findViewById(R.id.selectGirdView);
        selectGirdView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    view.setSelected(true);
                    if (detailJSON.optJSONObject(position).has("Main")==true) selDepart = detailJSON.optJSONObject(position).getString("Main");
                    if (detailJSON.optJSONObject(position).has("Sub")==true) selDepartNo = detailJSON.optJSONObject(position).getString("Sub");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        //显示表明细
        detailJSON=departJSON;
        SelectGridAdapter selectGridAdapter=new SelectGridAdapter(getContext());
        selectGirdView.setAdapter(selectGridAdapter);
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(selectGrid).setPositiveButton("确定", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        if (selDepart==null||selDepart.length() == 0) {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, false);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            curToast.setText("请点击要选择的内容！");
                            curToast.show();
                        } else{
                            btn_SelectDepart.setText("["+selDepartNo+"]"+selDepart);
                            refreshEmpList(selDepartNo);
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, true);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                }
        ).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    selDepart="";
                    Field field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                    field.setAccessible(true );
                    field.set(dialog,true );
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                Log.v("tag","取消");
            }
        }).setTitle(dgCaption);
        final AlertDialog alterDialog =builder.create();
        alterDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                //禁止两个按键上获取焦点，不然扫描框里就会失去焦点,在OnShow之前;
                System.out.println("alterDialog-setOnShowListener");
            }
        });
        alterDialog.show();
        //此处设置位置窗体大小
        WindowManager.LayoutParams params = alterDialog.getWindow().getAttributes();
        params.width = 750;
        params.height = 500 ;
        alterDialog.getWindow().setAttributes(params);
    }



    //数据适配器，继承自BaseAdapter;
    private final class SelectGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public SelectGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        public  String TrnasValue(String params)
        {
            if ((params.toUpperCase()=="NULL".toUpperCase())||(params=="0")||(params=="0.0"))
                return "";
            else return params;
        }
        @Override
        public int getCount() {
            //每页行数
            return detailJSON.length();
        }
        @Override
        public Object getItem(int position) {
            try {
                if (position<detailJSON.length())
                    return detailJSON.getJSONArray(position);
                else
                    return null;
            } catch (JSONException e)
            {
                e.printStackTrace();
                System.out.println("getItem取JSON数据出错!");
                return  null;
            }
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.select_grid_item, null, false);
            //转换分页码;
            int curPosition= position;
            String tmpValue;
            int color = Color.WHITE;
            if (curPosition<detailJSON.length()) {
                try {
                    Log.d(TAG, "getView()----------------------------------------------------->" + position);
                    TextView tv;
                    tv=view.findViewById(R.id.tv_MainItem);
                    if (detailJSON.optJSONObject(curPosition).has("Main")==true) {
                        tv.setText(detailJSON.optJSONObject(curPosition).getString("Main"));
                    } else tv.setVisibility(View.GONE);
                    tv=view.findViewById(R.id.tv_SubItem);
                    if (detailJSON.optJSONObject(curPosition).has("Sub")==true) {
                        tv.setText(detailJSON.optJSONObject(curPosition).getString("Sub"));
                    } else tv.setVisibility(view.GONE);
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
            return view;
        }
    }
    //判断是否为数字
    public static boolean isNumer(String str) {
        try {
            if (str.length() == 0) return false;
            for (int i = str.length(); --i >= 0; ) {
                if (!Character.isDigit(str.charAt(i))) {
                    return false;
                }
            }
            return true;
        }catch (Exception e){
            return false;
        }
    }

    //自动排车;
    private void autoPlace(String departParam,String orderParam,String styleParam,String paramStyleID,String paramStyleSort)
    {
        NeedReLoad=false;
        waitDialog.setMessage("正在请求自动排车服务，请稍后....");
        //执行SQL过程
        String SqlComm="Exec ScenePAD_AutoPlace @DepartmentNo='" + departParam + "',@OrderNo='"+orderParam+"',@StyleNo='"+styleParam+"',@StyleID='"+paramStyleID+"',@StyleSort='"+paramStyleSort+"'";
        //调用WebService过程并处理界面更新;
        ReadProcSQLData(SqlComm);
    }
    //显示工序选择
    private void selectStyle(){
        selectStyleID="";
        selectOrderNo ="";
        selectStyleNo="";
        selectStyleSort="";
        //创建布局
        LayoutInflater inflater=getActivity().getLayoutInflater();
        final View proc_stylefind=inflater.inflate(R.layout.fragment_proc_stylefind, null);
        procOrderListGrid=proc_stylefind.findViewById(R.id.procOrderListGrid);
        final Button btn_proc_style_find=proc_stylefind.findViewById(R.id.btn_proc_style_find);
        edit_orderNo=proc_stylefind.findViewById(R.id.edit_orderNo);
        edit_styleNo=proc_stylefind.findViewById(R.id.edit_styleNo);
        edit_orderNo.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                Log.d("edit_orderNo","setOnEditorActionListener---------------Start:"+actionId);
                Log.d("edit_orderNo","setOnEditorActionListener---------------KeyEvent:"+event);
                if (event!=null) {
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                        Log.d("edit_orderNo","setOnEditorActionListener---------------置焦点");
                        edit_styleNo.requestFocusFromTouch();//获取焦点 光标出现
                        edit_styleNo.requestFocus();
                    }
                }
                return false;
            }
        });
        edit_styleNo.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                Log.d("edit_styleNo","setOnEditorActionListener---------------Start:"+actionId);
                Log.d("edit_styleNo","setOnEditorActionListener---------------KeyEvent:"+event);
                if (event!=null){
                    if ((event.getAction()==KeyEvent.ACTION_DOWN)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        hideIM(v);
                        //执行登陆过程;
                        refreshOrderList(curDepartNo,edit_orderNo.getText().toString(),edit_styleNo.getText().toString(),"");
                    }
                }
                return false;
            }
        });
        edit_styleNo.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 获得焦点
                    Log.d("edit_styleNo","setOnFocusChangeListener---------------Start");
                    showIM(v);
                    Log.d("edit_styleNo","setOnFocusChangeListener---------------Over");
                } else {
                    // 失去焦点
                    hideIM(v);
                }
            }
        });
        btn_proc_style_find.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideIM(v);
                //调用数据;
                refreshOrderList(curDepartNo,edit_orderNo.getText().toString(),edit_styleNo.getText().toString(),"");
            }
        });
        procOrderListGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    selectStyleID= OrderJSONArray.getJSONObject(position).getString("StyleID");
                    selectOrderNo = OrderJSONArray.getJSONObject(position).getString("OrderNo");
                    selectStyleNo= OrderJSONArray.getJSONObject(position).getString("StyleNo");
                    selectStyleSort= OrderJSONArray.getJSONObject(position).getString("StyleSort");
                } catch (JSONException e) {
                    e.printStackTrace();
                    curToast.setText(e.getMessage());
                    curToast.show();
                }

            }
        });
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(proc_stylefind).setPositiveButton("确定", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        if (selectStyleID.length()>0) {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                                field.setAccessible(true );
                                field.set(dialog,true );
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            }
                            catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            //加载工序;
                            curOrderNo=selectOrderNo;
                            curStyleID=selectStyleID;
                            curStyleNo=selectStyleNo;
                            curStyleSort=selectStyleSort;
                            text_titleOrderNo.setText(curOrderNo);
                            text_titleStyleNo.setText(curStyleNo);
                            text_titleStyleSort.setText(curStyleSort);
                            refreshProcList(curDepartNo,curOrderNo,curStyleNo,curStyleID,curStyleSort,edit_workDate.getText().toString());
                        } else {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                                field.setAccessible(true );
                                field.set( dialog,false );
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            }
                            catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            curToast.setText("请通过点击选中需要查询的款式！");
                            curToast.show();
                        }
                    }
                }
        ).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Field field = null;
                try {
                    field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                    field.setAccessible(true );
                    field.set(dialog,true );
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                Log.v("tag","取消");
            }
        }).setTitle("选择需安排工序的制单");
        final AlertDialog alterDialog =builder.create();
        alterDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                //禁止两个按键上获取焦点，不然扫描框里就会失去焦点,在OnShow之前;
                System.out.println("alterDialog-setOnShowListener");
            }
        });
        alterDialog.show();
        //此处设置位置窗体大小
        WindowManager.LayoutParams params = alterDialog.getWindow().getAttributes();
        params.width = 900;
        params.height = 600 ;
        alterDialog.getWindow().setAttributes(params);

    }


    //工序表格适配器;
    public final class SelectOrderListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public SelectOrderListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return OrderJSONArray.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return OrderJSONArray.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.fragment_proc_styleitem, null, false);
            convertView.setBackground(getResources().getDrawable(R.drawable.orderlist_selector));
            int ct_max_background = getResources().getColor(R.color.ct_max_background);
            int ct_nor_background = getResources().getColor(R.color.ct_nor_background);
            int textColor=getResources().getColor(R.color.text_black);
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                TextView tv = (TextView) convertView.findViewById(R.id.text_proc_startdate);// 显示文字
                tv.setText(OrderJSONArray.optJSONObject(position).get("StartDate").toString());
                tv.setTextColor(textColor);
                tv = (TextView) convertView.findViewById(R.id.text_proc_orderno);// 显示文字
                tv.setText(OrderJSONArray.optJSONObject(position).get("OrderNo").toString());
                tv.setTextColor(textColor);
                tv = (TextView) convertView.findViewById(R.id.text_proc_styleno);// 显示文字
                tv.setText(OrderJSONArray.optJSONObject(position).get("StyleNo").toString());
                tv.setTextColor(textColor);
                tv = (TextView) convertView.findViewById(R.id.text_proc_stylesort);// 显示文字
                tv.setText(OrderJSONArray.optJSONObject(position).get("StyleSort").toString());
                tv.setTextColor(textColor);
                tv = (TextView) convertView.findViewById(R.id.text_proc_number);// 显示文字
                tv.setText(OrderJSONArray.optJSONObject(position).get("Number").toString());
                tv.setTextColor(textColor);
                tv = (TextView) convertView.findViewById(R.id.text_proc_samvalue);// 显示文字
                tv.setText(OrderJSONArray.optJSONObject(position).get("SAMValue").toString());
                tv.setTextColor(textColor);
            } catch (JSONException e) {
                e.printStackTrace();
                curToast.setText(e.getMessage());
                curToast.show();
            }
            Log.d("msg","SelectOrderListAdapter_position:"+position);
            return convertView;
        }
    }

    //保存工序安排
    private void SaveProcArrange(final String paramDepartNo, final String paramOrderNo, final String paramStyleNo, final String paramStyleID, final String paramStyleSort, final String paramWorkDate) {
        Log.d("SaveProcArrange","SaveProcArrange-----------------------------------------Enter");
        waitDialog.setMessage("正常上传工序安排表，请稍等...");
        waitDialog.show();
        if (tmpdb==null) OpenCreateDB();
        //更新人数;
        tmpdb.execSQL("Delete from EmpTotalCount");
        tmpdb.execSQL("update ProcList Set PlanEmpNum=0 where DepartNo=? and OrderNo=? and StyleNo=?",new  String[]{paramDepartNo,paramOrderNo,paramStyleNo});
        tmpdb.execSQL("INSERT OR REPLACE INTO EmpTotalCount(DepartNo,OrderNo,StyleNo,StyleProID,WorkNo,EmpCount) Select DepartNo,OrderNo,StyleNo,StyleProID,WorkNo,count(1) EmpCount From" +
                " EmpProcList  where length(empNo)>0 and DepartNo=? and OrderNo=? and StyleNo=? Group by DepartNo,OrderNo,StyleNo,StyleProID,WorkNo",new  String[]{paramDepartNo,paramOrderNo,paramStyleNo});
        tmpdb.execSQL("Update ProcList Set PlanEmpNum=(select EmpCount from EmpTotalCount where ProcList.DepartNo=EmpTotalCount.DepartNo and ProcList.OrderNo=EmpTotalCount.OrderNo " +
                "and ProcList.StyleNo=EmpTotalCount.StyleNo and ProcList.WorkNo=EmpTotalCount.WorkNo)");
        //线程直接保存不经过WebService;
        Runnable run = new Runnable() {
            @Override
            public void run() {
                String SqlComm;
                String SceneMaID = java.util.UUID.randomUUID().toString();
                //将数据读到JSONArray;
                try {
                    PreparedStatement pstmt = ToolUtil.getSQLConnection().prepareStatement("Insert into StyleSceneDe(SceneDeID,SceneMaID,ArrangeDeID,StyleProcID,WorkNo,WorkCT,WorkArrEmps,WorkArrEmpNos,PlaceNos,PlanEmpNum)values(newid(),?,?,?,?,?,?,?,?,?)");
                    Cursor cur = tmpdb.rawQuery("Select ArrangeDeID,StyleProID,WorkNo,WorkCT,WorkArrEmps,WorkArrEmpNos,PlaceNos,PlanEmpNum from ProcList where DepartNo=? and OrderNo=? and StyleNo=? and length(WorkArrEmps)>0 order by WorkLineNo", new String[]{paramDepartNo, paramOrderNo, paramStyleNo});
                    if (cur.getCount() > 0) {
                        while (cur.moveToNext()) {
                            pstmt.setString(1, SceneMaID);
                            pstmt.setString(2, cur.getString(cur.getColumnIndex("ArrangeDeID")));
                            pstmt.setString(3, cur.getString(cur.getColumnIndex("StyleProID")));
                            pstmt.setString(4, cur.getString(cur.getColumnIndex("WorkNo")));
                            pstmt.setString(5, cur.getString(cur.getColumnIndex("WorkCT")).length()>0?cur.getString(cur.getColumnIndex("WorkCT")):"0");
                            pstmt.setString(6, cur.getString(cur.getColumnIndex("WorkArrEmps")));
                            pstmt.setString(7, cur.getString(cur.getColumnIndex("WorkArrEmpNos")));
                            pstmt.setString(8, cur.getString(cur.getColumnIndex("PlaceNos")));
                            pstmt.setString(9, cur.getString(cur.getColumnIndex("PlanEmpNum")).length()>0?cur.getString(cur.getColumnIndex("PlanEmpNum")):"0");
                            pstmt.executeUpdate();
                        }
                    }
                    pstmt.close();
                    //增加主表;
                    //取CT，BudgetOut，BalanceRatio
                    cur=tmpdb.rawQuery("Select ArrangeID,CT,EmpCount,BudgetOut,BalanceRatio from ProcMaList where DepartNo=? and OrderNo=? and StyleNo=? ",new String[]{paramDepartNo,paramOrderNo,paramStyleNo});
                    String tmpCT = "0";
                    String tmpBudgetOut = "0";
                    String tmpBalanceRatio = "0";
                    String tmpArrangeID="";
                    String tmpEmpCount="0";
                    if (cur.getCount()>0) {
                        cur.moveToFirst();
                        tmpArrangeID= cur.getString(cur.getColumnIndex("ArrangeID"));
                        tmpCT = valueOf(cur.getInt(cur.getColumnIndex("CT")));
                        tmpEmpCount= valueOf(cur.getInt(cur.getColumnIndex("EmpCount")));
                        tmpBudgetOut = valueOf(cur.getInt(cur.getColumnIndex("BudgetOut")));
                        tmpBalanceRatio = valueOf(cur.getFloat(cur.getColumnIndex("BalanceRatio")));
                    }
                    pstmt = ToolUtil.getSQLConnection().prepareStatement(
                            "Insert into StyleSceneMa(SceneMaID,ArrangeID,DepartNo,OrderNo,StyleNo,StyleID,StyleSort,WorkDate,CT,EmpCount,BudgetOut,BalanceRatio,UserNo,WorkSection,CreateTime)" +
                                    " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,getdate())");
                    pstmt.setString(1, SceneMaID);
                    pstmt.setString(2, tmpArrangeID);
                    pstmt.setString(3, paramDepartNo);
                    pstmt.setString(4, paramOrderNo);
                    pstmt.setString(5, paramStyleNo);
                    pstmt.setString(6, paramStyleID);
                    pstmt.setString(7,paramStyleSort);
                    pstmt.setString(8, paramWorkDate);
                    pstmt.setString(9, tmpCT);
                    pstmt.setString(10, tmpEmpCount);
                    pstmt.setString(11, tmpBudgetOut);
                    pstmt.setString(12, tmpBalanceRatio);
                    pstmt.setString(13, curLoginUserNo);
                    pstmt.setString(14, WorkSection);
                    pstmt.executeUpdate();
                    pstmt.close();
                    //调用存储过程;
                    SqlComm = " Exec ScenePAD_TransSceneProc @SceneMaID='" + SceneMaID + "'";
                    JSONArray jsonArray  = ToolUtil.QuerySQL2JSON(SqlComm);
                    if ((jsonArray!=null)&&(jsonArray.length()>0)){
                        if (jsonArray.optJSONObject(0).has("PROCRESULT")){
                            //关闭ProgressDialog
                            Message msg = new Message();
                            msg.what = MSG_ERRMSG;
                            Bundle bundle=new Bundle();
                            bundle.putString("MSG",jsonArray.optJSONObject(0).getString("PROCRESULT"));
                            msg.setData(bundle);
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }

                    }
                    Log.d("SaveProcArrange","SaveProcArrange-----------------------------------------Over");
                } catch (SQLException | JSONException ex) {
                    ex.printStackTrace();
                    //关闭ProgressDialog
                    Message msg = new Message();
                    msg.what = MSG_ERRMSG;
                    Bundle bundle=new Bundle();
                    bundle.putString("MSG","保存安排方案出错!"+ex.getMessage());
                    msg.setData(bundle);
                    fragmentHandler.removeMessages(msg.what);
                    fragmentHandler.sendMessage(msg);
                }
            }

        };
        new Thread(run).start();

    }

    //增加工序到员工名下;
    private boolean AddEmpProc(){
        if (selPlaceNo.equals(null)==true) {
            curToast.setText("位置号为空，请选择！");
            curToast.show();
            return false;
        }
        if ((selEmpID==null)||(selEmpID.length()==0)){
            curToast.setText("请选择员工!");
            curToast.show();
            return false;
        }
        //提醒需保存安排方案
        btn_SaveProcScheme.setBackground(getResources().getDrawable(R.drawable.button_submitselector));
        //将工序安排给员工;
        if (tmpdb==null) OpenCreateDB();
        //将数据加载到empList中;
        try {
            boolean needInsert=true;
            for(int i=0;i<procList.length();i++) {
                Log.d("onClick","A-------------------");
                if (procList.getJSONObject(i).getBoolean("SelSign")==true) {
                    //取消选择状态;
                    procList.getJSONObject(i).put("SelSign",false);
                    String StyleProID=procList.getJSONObject(i).getString("StyleProID");
                    //默认需要增加安排;
                    needInsert = true;
                    Cursor curq=tmpdb.rawQuery("Select * from EmpProcList where DepartNo=? and EmpNo=? and StyleID=? and StyleProID=?"
                            ,new String[]{curDepartNo,selEmpNo,curStyleID,StyleProID});
                    if (curq.getCount()>0) {
                        needInsert = false;
                    }
                    if (needInsert==true)
                    {
                        //添加至工序列表;
                        String WorkArrEmps=procList.getJSONObject(i).getString("WorkArrEmps");
                        String WorkArrEmpNos=procList.getJSONObject(i).getString("WorkArrEmpNos");
                        String PlaceNos=procList.getJSONObject(i).getString("PlaceNos");
                        if (WorkArrEmps.length()>0) WorkArrEmps=WorkArrEmps+','+selEmpName;else WorkArrEmps=selEmpName;
                        if (WorkArrEmpNos.length()>0) WorkArrEmpNos=WorkArrEmpNos+','+selEmpNo;else WorkArrEmpNos=selEmpNo;
                        if (PlaceNos.length()>0) PlaceNos=PlaceNos+','+selPlaceNo;else PlaceNos=selPlaceNo;
                        procList.getJSONObject(i).put("WorkArrEmps",WorkArrEmps);
                        procList.getJSONObject(i).put("WorkArrEmpNos",WorkArrEmpNos);
                        procList.getJSONObject(i).put("PlaceNos",PlaceNos);
                        //更新相关字段;
                        tmpdb.execSQL("UPDATE ProcList SET WorkArrEmps=?,WorkArrEmpNos=?,PlaceNos=? WHERE StyleProID=? and DepartNo=?  and StyleID=?",
                                new String[]{WorkArrEmps,WorkArrEmpNos,PlaceNos,StyleProID,curDepartNo,curStyleID});
                        //插入相关字段
                        tmpdb.execSQL("INSERT INTO EmpProcList(DepartNo,EmpNo,EmpName,OrderNo,StyleNo,StyleID,StyleSort,StyleProID,WorkLineNo,WorkNo,WorkName,MachineName,SlowTime,PlaceNo) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                                new String[]{
                                        curDepartNo,selEmpNo,selEmpName,curOrderNo,curStyleNo,curStyleID,curStyleSort,StyleProID,
                                        procList.getJSONObject(i).getString("WorkLineNo"),
                                        procList.getJSONObject(i).getString("WorkNo"),
                                        procList.getJSONObject(i).getString("WorkName"),
                                        procList.getJSONObject(i).getString("MachineName"),
                                        procList.getJSONObject(i).getString("SlowTime"),selPlaceNo});
                        //更新到安排表;
                        int placeIndex=Integer.parseInt(selPlaceNo)-1;
                        arrMachineList.getJSONObject(placeIndex).put("EmpID",selEmpID);
                        arrMachineList.getJSONObject(placeIndex).put("EmpNo",selEmpNo);
                        arrMachineList.getJSONObject(placeIndex).put("EmpName",selEmpName);
                        arrMachineList.getJSONObject(placeIndex).put("MachineName",procList.getJSONObject(i).getString("MachineName"));
                        //显示当前位置员工对应工序;
                        String tmpWorkNames="";
                        Cursor cur=tmpdb.rawQuery("Select WorkLineNo,WorkNo,WorkName from EmpProcList where DepartNo=? and EmpNo=? and StyleID=? and PlaceNo=?"
                                ,new String[]{curDepartNo,selEmpNo,curStyleID,selPlaceNo});
                        while (cur.moveToNext()) {
                            String tmpWorkNo=cur.getString(cur.getColumnIndex("WorkNo"));
                            String tmpWorkName=cur.getString(cur.getColumnIndex("WorkName"));
                            if (tmpWorkName.length()>22) tmpWorkName=tmpWorkName.substring(0,22)+"...";
                            if (tmpWorkNames.length()>0) {
                                tmpWorkNames = tmpWorkNames+"\r\n"+tmpWorkNo+"."+tmpWorkName;
                            } else tmpWorkNames = tmpWorkNo+"."+tmpWorkName;
                        }
                        arrMachineList.getJSONObject(placeIndex).put("WorkNames",tmpWorkNames);
                        String tmpPlaceNo=arrMachineList.getJSONObject(placeIndex).getString("PlaceNo");
                        String tmpMachineName=arrMachineList.getJSONObject(placeIndex).getString("MachineName");
                        tmpdb.execSQL("Update ArrangeMachine Set EmpID=?,EmpNo=?,EmpName=?,MachineName=?,WorkNames=? where PlaceNo=?",new Object[]{selEmpID,selEmpNo,selEmpName,tmpMachineName,tmpWorkNames,tmpPlaceNo});
                    }
                }
            }
            //更新工作人数，预计产量及平衡率;
            updateBudgetOut(curDepartNo,curStyleID);
            //更新机台列表;
            ((BaseAdapter)arrMachineGrid.getAdapter()).notifyDataSetChanged();
            //更新工序列表;
            ((BaseAdapter)procListView.getAdapter()).notifyDataSetChanged();
            return true;
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }
    }

    //计算当前工序CT;
    private float CalcProCT(String paramDepartNo,String paramOrderNo,String paramStyleNo,String paramStyleID,String paramProID,float NormalTime){
        float TmpValue=0;
        float TmpSlowTime=0;
        Cursor cur=tmpdb.rawQuery("SELECT EmpNo,sum(SlowTime) SlowTime FROM EmpProcList where EmpNo IN (SELECT EmpNo from EmpProcList WHERE StyleProID=? and length(EmpNo)>0) and DepartNo=? and OrderNo=? and StyleNo=? and StyleID=?  GROUP BY EmpNo",
                new String[]{paramProID,paramDepartNo,paramOrderNo,paramStyleNo,paramStyleID});
        while (cur.moveToNext())
        {
            Log.d("MSG",cur.getString(cur.getColumnIndex("EmpNo"))+":"+cur.getInt(cur.getColumnIndex("SlowTime")));
            TmpSlowTime=cur.getInt(cur.getColumnIndex("SlowTime"));
            if(TmpSlowTime>0) TmpValue=TmpValue+NormalTime/TmpSlowTime;
        }
        cur.close();
        Log.d("CalcProCT:", valueOf(TmpValue));
        float TmpWorkCT=0;
        if (TmpValue>0) TmpWorkCT=(float)Math.floor(NormalTime/TmpValue*100)/100;
        return TmpWorkCT;
    }
    //更新当前合约的工作人数、预算产量、平衡率;
    private void updateBudgetOut(String paramDepartNo,String paramStyleID){
        if (tmpdb==null) OpenCreateDB();
        int tmpMaxWorkCT=0;
        int tmpTotalSlowTime=0;
        int tmpEmpCount=0;
        int tmpBudgetOut=0;
        double tmpBalanceRatio=0;
        //获取最大的CT;
        Cursor curA=tmpdb.rawQuery("Select Max(TotalSlowTime) MaxWorkCT from (SELECT EmpNo,Sum(SlowTime) TotalSlowTime FROM EmpProcList  where DepartNo=? and StyleID=? Group by EmpNo) b",
                new String[]{paramDepartNo,paramStyleID});
        if (curA.getCount()>0)
        {
            curA.moveToFirst();
            tmpMaxWorkCT=curA.getInt(curA.getColumnIndex("MaxWorkCT"));
        }
        curA=tmpdb.rawQuery("SELECT Sum(SlowTime) TotalSlowTime FROM EmpProcList  where DepartNo=? and StyleID=?",
                new String[]{paramDepartNo,paramStyleID});
        if (curA.getCount()>0)
        {
            curA.moveToFirst();
            tmpTotalSlowTime=curA.getInt(curA.getColumnIndex("TotalSlowTime"));
        }
        curA.close();
        //统计参与工作人数;
        Cursor curB=tmpdb.rawQuery("SELECT EmpNo,count(1) EmpProcCount FROM EmpProcList where length(EmpNo)>0 and DepartNo=? and StyleID=? Group by EmpNo",
                new String[]{paramDepartNo,paramStyleID});
        tmpEmpCount=curB.getCount();
        curB.close();
        //计算产量及平衡率;
        tmpBudgetOut=0;
        tmpBalanceRatio=0;
        if ((tmpMaxWorkCT>0)&&(tmpEmpCount>0))
        {
            System.out.println("tmpTotalSlowTime:"+tmpTotalSlowTime);
            System.out.println("tmpEmpCount:"+tmpEmpCount);
            System.out.println("tmpMaxWorkCT:"+tmpMaxWorkCT);
            tmpBudgetOut=curOperateTime*60/tmpMaxWorkCT;
            if (tmpEmpCount>0) tmpBalanceRatio=1.00*tmpTotalSlowTime/tmpEmpCount/tmpMaxWorkCT*100;
        }
        //更新到数据库中;
        tmpdb.execSQL("Update ProcMaList set CT=?,EmpCount=?,BudgetOut=?,BalanceRatio=? where DepartNo=? and StyleID=?",new Object[]{tmpMaxWorkCT,tmpEmpCount,tmpBudgetOut,tmpBalanceRatio,paramDepartNo,paramStyleID});
        //更新到界面字段;
        text_titleTT.setText(valueOf(tmpMaxWorkCT));
        text_ProcEmpCount.setText(valueOf(tmpEmpCount));
        text_ProcBudgetOut.setText(valueOf(tmpBudgetOut));
        text_ProcBalanceRatio.setText(String.format("%.2f",tmpBalanceRatio)+"%");
    }
    //清空员工名下工序;
    private boolean updateProcList(String paramDepartNo,  String paramStyleID){
        //提醒需保存安排方案
        btn_SaveProcScheme.setBackground(getResources().getDrawable(R.drawable.button_hintselector));
        //同步清除数据库内容;
        if (tmpdb==null) OpenCreateDB();
        try {
            for (int j = 0; j < procList.length(); j++) {
                String StyleProID = procList.getJSONObject(j).getString("StyleProID");
                Log.d("msg-Target", procList.getJSONObject(j).getString("WorkNo") + ":" + procList.getJSONObject(j).getString("StyleProID"));
                //重新整理;
                String WorkArrEmps = "";
                String WorkArrEmpNos = "";
                String PlaceNos = "";
                Cursor cur = tmpdb.rawQuery("SELECT * FROM EmpProcList WHERE DepartNo=? and StyleID=? and StyleProID=? ORDER BY PlaceNo",
                        new String[]{paramDepartNo, paramStyleID, StyleProID});
                while (cur.moveToNext()) {
                    if (WorkArrEmps.length() > 0)
                        WorkArrEmps = WorkArrEmps + "," + cur.getString(cur.getColumnIndex("EmpName"));
                    else WorkArrEmps = cur.getString(cur.getColumnIndex("EmpName"));
                    if (WorkArrEmpNos.length() > 0)
                        WorkArrEmpNos = WorkArrEmpNos + "," + cur.getString(cur.getColumnIndex("EmpNo"));
                    else WorkArrEmpNos = cur.getString(cur.getColumnIndex("EmpNo"));
                    if (PlaceNos.length() > 0)
                        PlaceNos = PlaceNos + "," + cur.getString(cur.getColumnIndex("PlaceNo"));
                    else PlaceNos = cur.getString(cur.getColumnIndex("PlaceNo"));
                }
                System.out.println("WorkArrEmps:"+WorkArrEmps);
                System.out.println("WorkArrEmpNos:"+WorkArrEmpNos);
                System.out.println("PlaceNos:"+PlaceNos);
                cur.close();
                //为界面刷新做准备;
                procList.getJSONObject(j).put("WorkArrEmps", WorkArrEmps);
                procList.getJSONObject(j).put("WorkArrEmpNos", WorkArrEmpNos);
                procList.getJSONObject(j).put("PlaceNos", PlaceNos);
                //更新相关字段;
                tmpdb.execSQL("UPDATE ProcList SET WorkArrEmps=?,WorkArrEmpNos=?,PlaceNos=? WHERE DepartNo=? and StyleID=? and StyleProID=?",
                        new String[]{WorkArrEmps, WorkArrEmpNos, PlaceNos, paramDepartNo,  paramStyleID, StyleProID});
            }
            //更新工作人数，预计产量及平衡率;
            updateBudgetOut(paramDepartNo,paramStyleID);
            //更新机台列表;
            ((BaseAdapter)arrMachineGrid.getAdapter()).notifyDataSetChanged();
            //更新工序列表;
            ((BaseAdapter)procListView.getAdapter()).notifyDataSetChanged();
            return true;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }

    //清空所有工序安排;
    private boolean ReEmpProc(String paramDepartNo,String paramOrderNo,String paramStyleNo,String paramStyleID,String paramStyleSort,String paramWorkDate) {
        if (tmpdb==null) OpenCreateDB();
        tmpdb.execSQL("UPDATE ProcList SET WorkArrEmps=?,WorkArrEmpNos=?,PlaceNos='',WorkCT=0 WHERE DepartNo=? AND OrderNo=? AND StyleNo=? AND StyleID=?",new String[]{"","",paramDepartNo,paramOrderNo,paramStyleNo,paramStyleID});
        tmpdb.execSQL("UPDATE EmpList SET EmpCT=0");
        tmpdb.execSQL("DELETE FROM EmpProcList where DepartNo=? AND OrderNo=? AND  StyleNo=? AND StyleID=?",new String[]{paramDepartNo,paramOrderNo,paramStyleNo,paramStyleID});
        tmpdb.execSQL("UPDATE ArrangeMachine Set EmpID=?,EmpNO=?,EmpName=?,WorkNames=?,MachineName=?",new String[]{"","","","",""});
        //刷新数据;
        showProcList();
        return false;
    }
    // /判断外部存储是否可读写
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }
    //打开数据库
    public void OpenCreateDB(){
        if (tmpdb==null) {
            MainActivity activity = (MainActivity) getActivity();
            tmpdb = activity.mainDB;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //隐藏输入法;
        hideIM(view);
        if (parent==empListView) {
            view.setSelected(true);
            if (selPlaceNo.equals(null)==true) {
                curToast.setText("位置号为空，请选择！");
                curToast.show();
            }
            //置当前选中的员工;
            try {
                selEmpID=empList.optJSONObject(position).getString("EmpID");
                selEmpNo=empList.optJSONObject(position).getString("EmpNo");
                selEmpName=empList.optJSONObject(position).getString("EmpName");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //更新显示;
            ((BaseAdapter)empListView.getAdapter()).notifyDataSetChanged();
            if (selPlaceNo.length()>0) {
                int placeIndex = Integer.parseInt(selPlaceNo) - 1;
                try {
                    if (arrMachineList.getJSONObject(placeIndex).getString("WorkNames").length()>0)
                    {
                        selPlaceNo = "";
                    } else {
                        arrMachineList.getJSONObject(placeIndex).put("EmpID",selEmpID);
                        arrMachineList.getJSONObject(placeIndex).put("EmpNo",selEmpNo);
                        arrMachineList.getJSONObject(placeIndex).put("EmpName",selEmpName);
                        //更新机台列表;
                        ((BaseAdapter)arrMachineGrid.getAdapter()).notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else
            {
                selPlaceNo = "";
            }
        }
        if (parent== procListView) {
            //置选择
            try {
                boolean curSelSign=procList.optJSONObject(position).getBoolean("SelSign");
                curSelSign=!curSelSign;
                procList.optJSONObject(position).put("SelSign",curSelSign);
                if (curSelSign==true) view.setBackgroundResource(R.drawable.procitem_sel_background); else {
                    view.setBackgroundResource(R.drawable.procitem_background);
                    if (procList.optJSONObject(position).get("WorkArrEmps").toString().length()>0)
                    {
                        if (procList.optJSONObject(position).get("WorkArrEmps").toString().length()>0)
                        {
                            ((TextView)view.findViewById(R.id.procGrid_ArrangeSign)).setTextColor(getResources().getColor(R.color.lightgray));
                        } else {
                            ((TextView)view.findViewById(R.id.procGrid_ArrangeSign)).setTextColor(Color.RED);
                        }
                    } else view.setBackgroundResource(R.drawable.procitem_background);
                }
                //如果员工已被选择
                //提醒需增加己选工序;
                if ((selEmpNo.length()>0)&&(selPlaceNo.length()>0)) {
                    btn_AddEmpProc.setBackgroundResource(R.drawable.button_hintselector);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (parent== arrMachineGrid) {
            try {
                selPlaceNo= valueOf(arrMachineList.optJSONObject(position).getInt("PlaceNo"));
                //根据位置上对应的员工显示;
                //置当前选中的员工;
                String tmpselEmpID=arrMachineList.optJSONObject(position).getString("EmpID");
                String tmpselWorkNames=arrMachineList.optJSONObject(position).getString("WorkNames");
                if (tmpselEmpID.length()>0) {
                    selEmpID = arrMachineList.optJSONObject(position).getString("EmpID");
                    selEmpNo = arrMachineList.optJSONObject(position).getString("EmpNo");
                    selEmpName = arrMachineList.optJSONObject(position).getString("EmpName");
                } else{
                    if (tmpselWorkNames.length()==0){
                        arrMachineList.optJSONObject(position).put("EmpID",selEmpID);
                        arrMachineList.optJSONObject(position).put("EmpNo",selEmpNo);
                        arrMachineList.optJSONObject(position).put("EmpName",selEmpName);
                        //更新机台列表;
                        ((BaseAdapter)arrMachineGrid.getAdapter()).notifyDataSetChanged();
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


    public final class ProcGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public ProcGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return procList.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return procList.get(position);
            } catch (JSONException e) {
                System.out.println("getItem取JSON数据出错!");
                e.printStackTrace();
                return  null;
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.fragment_proc_procitem, null, false);
            int ct_max_background = getResources().getColor(R.color.ct_max_background);
            int ct_nor_background = getResources().getColor(R.color.ct_nor_background);
            try {
                boolean curSelSign=procList.optJSONObject(position).getBoolean("SelSign");
                if (curSelSign==true) convertView.setBackgroundResource(R.drawable.procitem_sel_background); else {
                    convertView.setBackgroundResource(R.drawable.procitem_background);
                    if ((procList.optJSONObject(position).has("WorkArrEmps"))&&(procList.optJSONObject(position).get("WorkArrEmps").toString().length()>0))
                    {
                        ((TextView)convertView.findViewById(R.id.procGrid_ArrangeSign)).setTextColor(getResources().getColor(R.color.lightgray));
                    } else {
                        ((TextView)convertView.findViewById(R.id.procGrid_ArrangeSign)).setTextColor(Color.RED);
                    }
                }
                TextView tv = (TextView) convertView.findViewById(R.id.procGrid_workNoText);// 显示文字
                tv.setText(procList.optJSONObject(position).get("WorkNo").toString());
                tv = (TextView) convertView.findViewById(R.id.procGrid_workNameText);// 显示文字
                tv.setText(procList.optJSONObject(position).get("WorkName").toString());
                tv = (TextView) convertView.findViewById(R.id.procGrid_MachineNameText);// 显示文字
                tv.setText(procList.optJSONObject(position).get("MachineName").toString());
                tv = (TextView) convertView.findViewById(R.id.procGrid_SlowTimeText);// 显示文字
                tv.setText(procList.optJSONObject(position).get("SlowTime").toString());
                tv = (TextView) convertView.findViewById(R.id.procGrid_CTText);// 显示文字
                tv.setText(procList.optJSONObject(position).getString("WorkCT"));
                tv = (TextView) convertView.findViewById(R.id.procGrid_PartText);// 显示文字
                tv.setText(procList.optJSONObject(position).get("Part").toString());
                if (procList.getJSONObject(position).getString("BaseKey").equals("true")){
                    tv.setTextColor(getResources().getColor(R.color.orchid));
                } else tv.setTextColor(getResources().getColor(R.color.ProcItemParttext));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return convertView;
        }
    }


    @Override
    public void onStart() {
        super.onStart();
        Log.d("msg", "ProcFragment.onStart-----------------重新开始");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d("msg", "ProcFragment.onResume-----------------重新激活");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d("msg", "onPause-----------------切换时暂停");
    }
}
